//
//  StatusPicture.swift
//  Microblog
//
//  Created by steaest on 15/8/7.
//  Copyright © 2015年 steaest. All rights reserved.
//

import UIKit
import SDWebImage

private let statusPictureCellID = "statusPictureCellID"

class StatusPicture: UICollectionView {
    
    //微博模型数组
    var status:Status? {
        didSet {
            //sizeToFit会调用sizeThatFits
            sizeToFit()
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    //计算视图的大小
    private func calcViewSize() -> CGSize {
    
        //1.准备常量
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        //每一行能够显示的图片数量
        let rowCount = 3
        
        pictureLayout.itemSize = itemSize
        //2.根据图片数量计算视图大小
        let count = status?.pictureURLs?.count ?? 0

        //没有图片
        if count == 0 {
            return CGSizeZero
        }
        //1张图片
        if count == 1 {
            
            let key = status!.pictureURLs![0].absoluteString

            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            //如果不存在的默认大小
            var size = CGSize(width: 150, height: 120)
            
            if image != nil {
                size = image.size
            }
            
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > UIScreen.mainScreen().bounds.size.width ? 150 : size.width
        
            pictureLayout.itemSize = size
            return size
        }
        //4张图片
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return CGSize(width: w, height: w)
        }
        //其他
        /**
        2,3
        5,6
        7,8,9
        */
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(rowCount - 1) * margin
        return CGSize(width: w, height: h)
    }

    //初始化
    let pictureLayout = UICollectionViewFlowLayout()
    //调用父类的构造函数之前,需给本类初始化
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        registerClass(statusPictureCell.self, forCellWithReuseIdentifier: statusPictureCellID)
        self.dataSource = self
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

//MARK: - 数据源方法
// 在 swift 中，协议同样可以通过 extension 来写，可以将一组协议方法，放置在一起，便于代码维护和阅读！
extension StatusPicture: UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictureCellID, forIndexPath: indexPath) as! statusPictureCell
        cell.imageURL = status?.pictureURLs![indexPath.item]
        
        return cell
    }
}

//MARK: - 自定义UICollectionViewCell
class statusPictureCell: UICollectionViewCell {

    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL!)
        }
    }
    
    //构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
    
        contentView.addSubview(iconView)
        iconView.ff_Fill(contentView)
    }
    
    //懒加载控件
    private lazy var iconView: UIImageView = {
        
        let icon = UIImageView()
        
        //设置多图的等比例缩放
        icon.contentMode = UIViewContentMode.ScaleAspectFill
        
        icon.clipsToBounds = true
        
        return icon
        }()
}


